package flc.ast.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.LocalVideoActivity;
import flc.ast.activity.PlayActivity;
import flc.ast.activity.PlayLinkActivity;
import flc.ast.activity.SelVideoActivity;
import flc.ast.adapter.VideoAdapter;
import flc.ast.bean.MyCollectBean;
import flc.ast.bean.MyVideoBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private List<MyVideoBean> list = new ArrayList<>();//全部数据
    private VideoAdapter videoAdapter;
    private Dialog myDeleteDialog;
    private MyVideoBean bean;


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.tvVideoMore.setOnClickListener(this);
        mDataBinding.ivPlayLink.setOnClickListener(this);
        mDataBinding.ivVideoFormat.setOnClickListener(this);
        mDataBinding.tvVideoNoPermission.setOnClickListener(this);
        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        videoAdapter = new VideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemCollect);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemShare);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemDelete);
        videoAdapter.setOnItemChildClickListener(this);
        videoAdapter.setOnItemClickListener(this);
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvVideoMore://查看更多
                startActivity(LocalVideoActivity.class);
                break;
            case R.id.ivPlayLink://链接播放
                startActivity(PlayLinkActivity.class);
                break;
            case R.id.ivVideoFormat://格式转换
                SelVideoActivity.isMoreSel=false;
                startActivity(SelVideoActivity.class);
                break;
            case R.id.ivDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            case R.id.ivDialogDeleteRight://确定
                getManagePermission(bean);
                break;
            case R.id.tvVideoNoPermission://暂无权限
                getPermission();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayActivity.videoPath=videoAdapter.getItem(position).getPath();
        startActivity(PlayActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        bean = videoAdapter.getItem(position);
        switch (view.getId()) {
            case R.id.ivVideoItemCollect:
                List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                if (videoAdapter.getItem(position).isCollect()) {
                    for (MyCollectBean myCollectBean : listSp) {
                        if (myCollectBean.getPath().equals(bean.getPath())) {
                            listSp.remove(myCollectBean);
                            break;
                        }
                    }
                    AppSpUtils.saveCollectList(listSp);
                } else {
                    List<MyCollectBean> listSave = new ArrayList<>();
                    listSave.add(new MyCollectBean(bean.getName(), bean.getPath(), bean.getDate()));
                    if (listSp != null && listSp.size() != 0) {
                        listSp.addAll(listSave);
                        AppSpUtils.saveCollectList(listSp);
                    } else {
                        AppSpUtils.saveCollectList(listSave);
                    }
                }
                getData();
                break;
            case R.id.ivVideoItemShare:
                IntentUtil.shareVideo(mContext, bean.getPath());
                break;
            case R.id.ivVideoItemDelete:
                myDeleteDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        if (StkPermissionHelper.hasGrantMediaImgVideoPermission()){
            getData();
        }else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
            mDataBinding.tvVideoNoPermission.setVisibility(View.VISIBLE);
        }
//        getPermission();
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO).reqPermissionDesc(getString(R.string.get_storage_permission_home)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                getData();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                mDataBinding.rvVideoList.setVisibility(View.GONE);
            }
        }).request();
    }

    //获取视频和图片数据
    private void getData() {
        list.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                    for (SelectMediaEntity bean : selectMediaEntities) {
                        boolean isCollect = false;
                        if (listSp != null && listSp.size() != 0) {
                            for (MyCollectBean myCollectBean : listSp) {
                                if (myCollectBean.getPath().equals(bean.getPath())) {
                                    isCollect = true;
                                    break;
                                }
                            }
                        }
                        list.add(new MyVideoBean(bean.getMediaName(), bean.getPath(), bean.getUri(), bean.getDuration(), FileUtils.getFileLastModified(bean.getPath()), false, isCollect));
                    }
                    if (list.size()>3){
                        list = list.subList(0, 3);
                    }
                    videoAdapter.setList(list);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoData.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoPermission.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoPermission.setVisibility(View.GONE);
                }
            }
        });
    }

    //文件管理权限
    private void getManagePermission(MyVideoBean bean) {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_manage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        deleteVideo(bean);
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(getString(R.string.get_manage_permission));
                    }
                }).request();
    }

    //删除视频
    private void deleteVideo(MyVideoBean bean) {
        myDeleteDialog.dismiss();
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        mContext.getContentResolver().delete(Uri.parse(bean.getUrl()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        getData();
                    }
                });
            }
        }, 500);
    }

    //删除提示
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView dialogConfirm = inflate.findViewById(R.id.ivDialogDeleteRight);
        dialogCancel.setOnClickListener(this);
        dialogConfirm.setOnClickListener(this);
    }

}